package com.plate.auth.controller;

import com.plate.auth.domain.LoginBO;
import com.plate.common.core.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SysUserController
 * @Description TODO
 * @Author jiaxd
 * @Date 2023年10月18日 21:37
 * @Version 1.0
 */

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Lazy
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/login")
    public Result login(@RequestBody LoginBO loginBO) throws HttpRequestMethodNotSupportedException {

        User clientUser = new User("jiaxiaodong", "123456", new ArrayList<>());

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(clientUser, null, new ArrayList<>());
        //封装成一个UserPassword方式的参数体
        Map<String, String> map = new HashMap<>();
        map.put("username", loginBO.getUsername());
        map.put("password", loginBO.getPassword());
        //授权模式为：密码模式
        map.put("grant_type", "password");

        //调用自带的获取token方法。
        OAuth2AccessToken resultToken = tokenEndpoint.postAccessToken(token, map).getBody();

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("access_token", resultToken.getValue());
        resMap.put("token_type", resultToken.getTokenType());
        resMap.put("refresh_token", resultToken.getRefreshToken());
        resMap.put("expires_in", resultToken.getExpiresIn());
        resMap.put("scope", resultToken.getScope());
        return Result.SUCCESS(resMap);
    }

}
